import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/model/user/user_model.dart';
import 'package:labcloud_app/model/user/user_wallet_model.dart';

class WalletPage extends StatefulWidget {
  const WalletPage({super.key});

  @override
  State<WalletPage> createState() => _WalletPageState();
}

class _WalletPageState extends State<WalletPage> {
  bool _isLoading = true;
  String _errorMessage = '';
  bool _isLoadWalletCalled = false;

  Future<void> _loadWallet(UserModel userModel, UserWalletModel walletModel) async {
    try {
      final client = GraphQLProvider.of(context).value;
      
      if (userModel.isLoggedIn) {
        await walletModel.loadWallet(client);
      }
      
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载钱包信息失败: $e';
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer2<UserModel, UserWalletModel>(
      builder: (context, userModel, walletModel, child) {
        // 当用户模型初始化完成且还未调用加载钱包时，执行加载操作
        if (userModel.isLoggedIn && !_isLoadWalletCalled) {
          _isLoadWalletCalled = true;
          WidgetsBinding.instance.addPostFrameCallback((_) {
            _loadWallet(userModel, walletModel);
          });
        }

        // 检查用户是否登录
        if (!userModel.isLoggedIn) {
          return Scaffold(
            appBar: AppBar(
              title: const Text('我的钱包'),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.account_balance_wallet,
                    size: 80,
                    color: Colors.grey,
                  ),
                  const SizedBox(height: 20),
                  const Text(
                    '请先登录',
                    style: TextStyle(
                      fontSize: 18,
                      color: Colors.grey,
                    ),
                  ),
                  const SizedBox(height: 30),
                  ElevatedButton(
                    onPressed: () {
                      // 导航到登录页面
                      Navigator.pushNamed(context, '/login');
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 15),
                    ),
                    child: const Text('去登录'),
                  ),
                ],
              ),
            ),
          );
        }

        if (_isLoading || walletModel.isLoading) {
          return Scaffold(
            appBar: AppBar(
              title: const Text('我的钱包'),
            ),
            body: const Center(child: CircularProgressIndicator()),
          );
        }

        if (_errorMessage.isNotEmpty || walletModel.errorMessage.isNotEmpty) {
          String errorMessage = _errorMessage.isNotEmpty 
              ? _errorMessage 
              : walletModel.errorMessage;
              
          return Scaffold(
            appBar: AppBar(
              title: const Text('我的钱包'),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(errorMessage),
                  ElevatedButton(
                    onPressed: () {
                      setState(() {
                        _isLoading = true;
                        _errorMessage = '';
                        _isLoadWalletCalled = false;
                      });
                      _loadWallet(userModel, walletModel);
                    },
                    child: const Text('重试'),
                  ),
                ],
              ),
            ),
          );
        }

        // 检查是否有钱包
        if (walletModel.hasWallet) {
          return Scaffold(
            appBar: AppBar(
              title: const Text('我的钱包'),
            ),
            body: _buildWalletContent(userModel, walletModel),
          );
        } else {
          return Scaffold(
            appBar: AppBar(
              title: const Text('我的钱包'),
            ),
            body: _buildOpenWalletContent(userModel, walletModel),
          );
        }
      },
    );
  }

  // 构建钱包内容
  Widget _buildWalletContent(UserModel userModel, UserWalletModel walletModel) {
    String? balance = walletModel.balance; // 保持为 String? 类型

    return Column(
      children: [
        // 钱包余额展示
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(30),
          margin: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            color: Colors.blue,
            borderRadius: BorderRadius.circular(15),
            boxShadow: [
              BoxShadow(
                color: Colors.blue.withOpacity(0.3),
                blurRadius: 10,
                offset: const Offset(0, 5),
              ),
            ],
          ),
          child: Column(
            children: [
              const Text(
                '账户余额（元）',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                ),
              ),
              const SizedBox(height: 10),
              Text(
                balance ?? '0.00', // 使用 null 合并操作符提供默认值
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 36,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),

        const SizedBox(height: 30),

        // 功能按钮
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  onPressed: () => _recharge(userModel, walletModel),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 15),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                  child: const Text(
                    '充值',
                    style: TextStyle(fontSize: 16),
                  ),
                ),
              ),
              const SizedBox(width: 20),
              Expanded(
                child: ElevatedButton(
                  onPressed: _withdraw,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    foregroundColor: Colors.blue,
                    side: const BorderSide(color: Colors.blue),
                    padding: const EdgeInsets.symmetric(vertical: 15),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                  child: const Text(
                    '提现',
                    style: TextStyle(fontSize: 16),
                  ),
                ),
              ),
            ],
          ),
        ),

        const SizedBox(height: 30),

        // 钱包功能说明
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(20),
          margin: const EdgeInsets.symmetric(horizontal: 20),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10),
            border: Border.all(color: Colors.grey.shade300),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '钱包说明',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 10),
              const Text('• 钱包余额可用于购买商品'),
              const Text('• 充值即时到账'),
              const Text('• 提现将在1-3个工作日内到账'),
              const Text('• 提现手续费：0.1%'),
              const SizedBox(height: 10),
              // 这里可以添加设置支付密码的逻辑
              TextButton(
                onPressed: () => _openWallet(userModel, walletModel),
                child: const Text('设置支付密码'),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 构建开通钱包内容
  Widget _buildOpenWalletContent(UserModel userModel, UserWalletModel walletModel) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.account_balance_wallet_outlined,
            size: 100,
            color: Colors.grey,
          ),
          const SizedBox(height: 20),
          const Text(
            '您还没有开通钱包',
            style: TextStyle(
              fontSize: 20,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 10),
          const Text(
            '开通钱包，享受便捷支付体验',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 30),
          ElevatedButton(
            onPressed: () => _openWallet(userModel, walletModel),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 15),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(30),
              ),
            ),
            child: const Text(
              '开通钱包',
              style: TextStyle(
                fontSize: 16,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 开通钱包
  void _openWallet(UserModel userModel, UserWalletModel walletModel) {
    // 显示设置支付密码对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return _buildSetPaymentPasswordDialog(userModel, walletModel);
      },
    );
  }

  // 构建设置支付密码对话框
  Widget _buildSetPaymentPasswordDialog(UserModel userModel, UserWalletModel walletModel) {
    final TextEditingController passwordController = TextEditingController();
    final TextEditingController confirmPasswordController = TextEditingController();

    return AlertDialog(
      title: const Text('设置支付密码'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text('为了您的资金安全，请设置6位数字支付密码'),
          const SizedBox(height: 15),
          TextField(
            controller: passwordController,
            keyboardType: TextInputType.number,
            obscureText: true,
            maxLength: 6,
            decoration: const InputDecoration(
              hintText: '请输入6位数字支付密码',
              border: OutlineInputBorder(),
            ),
          ),
          const SizedBox(height: 10),
          TextField(
            controller: confirmPasswordController,
            keyboardType: TextInputType.number,
            obscureText: true,
            maxLength: 6,
            decoration: const InputDecoration(
              hintText: '请再次输入支付密码',
              border: OutlineInputBorder(),
            ),
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('取消'),
        ),
        TextButton(
          onPressed: () {
            final password = passwordController.text;
            final confirmPassword = confirmPasswordController.text;

            if (password.isEmpty || confirmPassword.isEmpty) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('请输入完整的密码信息')),
              );
              return;
            }

            if (password.length != 6 || confirmPassword.length != 6) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('支付密码必须为6位数字')),
              );
              return;
            }

            if (!RegExp(r'^\d{6}$').hasMatch(password)) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('支付密码必须为6位数字')),
              );
              return;
            }

            if (password != confirmPassword) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('两次输入的密码不一致')),
              );
              return;
            }

            // 使用GraphQL开通钱包
            _openWalletWithGraphQL(userModel, walletModel, password);
          },
          child: const Text('确定'),
        ),
      ],
    );
  }

  // 使用GraphQL开通钱包
  void _openWalletWithGraphQL(UserModel userModel, UserWalletModel walletModel, String payPassword) async {
    try {
      final client = GraphQLProvider.of(context).value;

      final success = await walletModel.openWallet(client, payPassword: payPassword);

      if (!success) {
        if (mounted) {
          Navigator.pop(context);
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('钱包开通失败: ${walletModel.errorMessage}')),
          );
        }
      } else {
        if (mounted) {
          Navigator.pop(context);
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('钱包开通成功')),
          );

          // 重新加载页面以显示钱包信息
          setState(() {
            _isLoading = true;
            _errorMessage = '';
            _isLoadWalletCalled = false;
          });
        }
      }
    } catch (e) {
      if (mounted) {
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('钱包开通失败: $e')),
        );
      }
    }
  }

  // 充值
  void _recharge(UserModel userModel, UserWalletModel walletModel) {
    // 显示充值对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return _buildRechargeDialog(userModel, walletModel);
      },
    );
  }

  // 提现
  void _withdraw() {
    // 显示提现对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return _buildWithdrawDialog();
      },
    );
  }

  // 构建充值对话框
  Widget _buildRechargeDialog(UserModel userModel, UserWalletModel walletModel) {
    final TextEditingController amountController = TextEditingController();
    String? selectedChannel = 'alipay'; // 默认选择支付宝

    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        return AlertDialog(
          title: const Text('充值'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('请输入充值金额'),
              const SizedBox(height: 10),
              TextField(
                controller: amountController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  hintText: '金额（元）',
                  prefixText: '¥ ',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 15),
              const Text('选择充值渠道'),
              const SizedBox(height: 10),
              DropdownButtonFormField<String>(
                value: selectedChannel,
                items: const [
                  DropdownMenuItem(
                    value: 'alipay',
                    child: Row(
                      children: [
                        Icon(Icons.account_balance_wallet, color: Colors.blue),
                        SizedBox(width: 10),
                        Text('支付宝'),
                      ],
                    ),
                  ),
                  DropdownMenuItem(
                    value: 'wechat',
                    child: Row(
                      children: [
                        Icon(Icons.account_balance_wallet, color: Colors.green),
                        SizedBox(width: 10),
                        Text('微信支付'),
                      ],
                    ),
                  ),
                  DropdownMenuItem(
                    value: 'bank',
                    child: Row(
                      children: [
                        Icon(Icons.account_balance, color: Colors.orange),
                        SizedBox(width: 10),
                        Text('银行卡'),
                      ],
                    ),
                  ),
                ],
                onChanged: (String? value) {
                  setState(() {
                    selectedChannel = value;
                  });
                },
                decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                final amount = double.tryParse(amountController.text);
                if (amount != null && amount > 0) {
                  // 验证支付密码
                  _showPaymentPasswordDialog(
                    context: context,
                    onSuccess: (password) {
                      // 使用GraphQL充值
                      _rechargeWithGraphQL(
                        walletModel: walletModel,
                        amount: amount,
                        channelType: selectedChannel!, 
                        payPassword: password,
                      );
                    },
                    onCancel: () {
                      Navigator.pop(context); // 关闭支付密码对话框
                    },
                  );
                } else {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('请输入有效的金额')),
                  );
                }
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  // 使用GraphQL充值
  void _rechargeWithGraphQL({
    required UserWalletModel walletModel,
    required double amount,
    required String channelType,
    required String payPassword, // 这个参数暂时未使用，但在实际项目中应该验证支付密码
  }) async {
    try {
      final client = GraphQLProvider.of(context).value;

      final success = await walletModel.rechargeWallet(
        client,
        amount: amount.toStringAsFixed(2),
        channelType: channelType,
        channelId: "123", // 这里应该根据实际渠道类型设置正确的channelId
        payPassword: payPassword, // 添加支付密码参数
      );

      if (!success) {
        if (mounted) {
          Navigator.pop(context); // 关闭支付密码对话框
          Navigator.pop(context); // 关闭充值对话框
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('充值失败: ${walletModel.errorMessage}')),
          );
        }
      } else {
        if (mounted) {
          Navigator.pop(context); // 关闭支付密码对话框
          Navigator.pop(context); // 关闭充值对话框
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('充值成功，充值金额：¥${amount.toStringAsFixed(2)}')),
          );

          // 重新加载页面以更新余额
          setState(() {
            _isLoading = true;
            _errorMessage = '';
            _isLoadWalletCalled = false;
          });
        }
      }
    } catch (e) {
      if (mounted) {
        Navigator.pop(context); // 关闭支付密码对话框
        Navigator.pop(context); // 关闭充值对话框
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('充值失败: $e')),
        );
      }
    }
  }

  // 构建提现对话框
  Widget _buildWithdrawDialog() {
    final TextEditingController amountController = TextEditingController();
    String? selectedChannel = 'bank'; // 默认选择银行卡

    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        return AlertDialog(
          title: const Text('提现'),
          content: Consumer<UserWalletModel>(
            builder: (context, walletModel, child) {
              String? balance = walletModel.balance;
              double balanceValue = double.tryParse(balance ?? '0') ?? 0.0;

              return Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Text('请输入提现金额'),
                  const SizedBox(height: 10),
                  TextField(
                    controller: amountController,
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                      hintText: '金额（元）',
                      prefixText: '¥ ',
                      border: OutlineInputBorder(),
                      helperText: '当前余额：¥${balance ?? '0.00'}',
                    ),
                  ),
                  const SizedBox(height: 15),
                  const Text('选择提现渠道'),
                  const SizedBox(height: 10),
                  DropdownButtonFormField<String>(
                    value: selectedChannel,
                    items: const [
                      DropdownMenuItem(
                        value: 'alipay',
                        child: Row(
                          children: [
                            Icon(Icons.account_balance_wallet, color: Colors.blue),
                            SizedBox(width: 10),
                            Text('支付宝'),
                          ],
                        ),
                      ),
                      DropdownMenuItem(
                        value: 'wechat',
                        child: Row(
                          children: [
                            Icon(Icons.account_balance_wallet, color: Colors.green),
                            SizedBox(width: 10),
                            Text('微信支付'),
                          ],
                        ),
                      ),
                      DropdownMenuItem(
                        value: 'bank',
                        child: Row(
                          children: [
                            Icon(Icons.account_balance, color: Colors.orange),
                            SizedBox(width: 10),
                            Text('银行卡'),
                          ],
                        ),
                      ),
                    ],
                    onChanged: (String? value) {
                      setState(() {
                        selectedChannel = value;
                      });
                    },
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                    ),
                  ),
                ],
              );
            }
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                final amount = double.tryParse(amountController.text);
                String? balance = context.read<UserWalletModel>().balance;
                double balanceValue = double.tryParse(balance ?? '0') ?? 0.0;

                if (amount != null && amount > 0 && amount <= balanceValue) {
                  // 验证支付密码
                  _showPaymentPasswordDialog(
                    context: context,
                    onSuccess: (password) {
                      Navigator.pop(context); // 关闭支付密码对话框
                      Navigator.pop(context); // 关闭提现对话框
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(content: Text('提现成功，提现金额：¥$amount')),
                      );

                      // 重新加载钱包数据以更新余额
                      setState(() {
                        _isLoading = true;
                        _errorMessage = '';
                        _isLoadWalletCalled = false;
                      });
                    },
                    onCancel: () {
                      Navigator.pop(context); // 关闭支付密码对话框
                    },
                  );
                } else if (amount != null && amount > balanceValue) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('提现金额不能超过余额')),
                  );
                } else {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('请输入有效的金额')),
                  );
                }
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  // 显示支付密码验证对话框
  void _showPaymentPasswordDialog({
    required BuildContext context,
    required void Function(String password) onSuccess,
    required VoidCallback onCancel,
  }) {
    final TextEditingController passwordController = TextEditingController();

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('输入支付密码'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('请输入6位数字支付密码'),
              const SizedBox(height: 15),
              TextField(
                controller: passwordController,
                keyboardType: TextInputType.number,
                obscureText: true,
                maxLength: 6,
                decoration: const InputDecoration(
                  hintText: '请输入支付密码',
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                onCancel();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                final password = passwordController.text;

                if (password.isEmpty) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('请输入支付密码')),
                  );
                  return;
                }

                if (password.length != 6 || !RegExp(r'^\d{6}$').hasMatch(password)) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('支付密码必须为6位数字')),
                  );
                  return;
                }

                // 这里应该验证支付密码是否正确
                // 模拟验证成功
                onSuccess(password);
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }
}